在上一篇我們已將程式重構為
<?php
// src/PttCrawler.php
namespace Recca0120\Ithome30;
use Psr\Http\Client\ClientInterface;
use Recca0120\Ithome30\Crawlers\Home;
class PttCrawler
{
public function __construct(private ClientInterface $httpClient)
{
}
public function all()
{
$crawler = new Home($this->httpClient);
return $crawler->all();
}
}
接下來要開始分析每個看版的列表,這時候可以先打開原本的測試
<?php
namespace Recca0120\Ithome30\Tests;
use Mockery;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use PHPUnit\Framework\TestCase;
use Recca0120\Ithome30\PttCrawler;
use Psr\Http\Client\ClientInterface;
class PttCrawlerTest extends TestCase
{
public function test_fetch_board_page()
{
\VCR\VCR::turnOn();
\VCR\VCR::insertCassette('ptt_home.yaml');
/** @var Mockery\Mock|ClientInterface $httpClient */
$httpClient = Mockery::spy(new Client());
$crawler = new PttCrawler($httpClient);
$records = $crawler->all();
self::assertEquals([
'name' => 'Gossiping',
"nuser" => '8803',
'class' => '綜合',
'title' => '[八卦] 亞運李智凱、許皓鋐奪金!',
'url' => 'https://www.ptt.cc/bbs/Gossiping/index.html'
], $records[0]);
$httpClient->shouldHaveReceived('sendRequest')->once()->with(Mockery::on(function (Request $request) {
return (((string)$request->getUri()) === 'https://www.ptt.cc/bbs/hotboards.html');
}));
\VCR\VCR::eject();
\VCR\VCR::turnOff();
}
}
可以先思考回傳的結果的格式是什麼,怎麼比較容易存入資料庫。所以目前想到的方案有
self::assertEquals([
'name' => 'Gossiping',
"nuser" => '8803',
'class' => '綜合',
'title' => '[八卦] 亞運李智凱、許皓鋐奪金!',
'url' => 'https://www.ptt.cc/bbs/Gossiping/index.html'
'children' => [
[
'nrec' => '4',
'type' => '協尋',
'title' => '9/30 10:15員林回春中醫診所前車禍行車',
'author' => 'tyujm',
'date' => '10/3',
'url' => 'https://www.ptt.cc/bbs/Gossiping/M.1696296400.A.A9B.html',
]
],
], $records[0]);
self::assertEquals([
'board_name' => 'Gossiping',
'board_class' => '綜合',
'nrec' => '4',
'type' => '協尋',
'title' => '9/30 10:15員林回春中醫診所前車禍行車',
'author' => 'tyujm',
'date' => '10/3',
'url' => 'https://www.ptt.cc/bbs/Gossiping/M.1696296400.A.A9B.html',
], $records[0]);
分析了這兩個方案之後,我打算採取第 2 個方案,原因是資料取出後只需要跑一次迴圈就可以,比較方便使用
這是目前預期的結果,最後寫出來的程式如果不容易使用,我們還是保有測試隨時可以進行調整
確認好方案之後我們接下來就是面臨的議題就是『測試要怎麼寫才對』的情境了,明天我們再來探討這個問題